import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Statistic, List, Table, Progress, Tag, Avatar, Button, Space, Divider, Alert, Tooltip } from 'antd';
import { 
  FileTextOutlined, 
  TeamOutlined, 
  ApiOutlined, 
  RocketOutlined,
  BarChartOutlined,
  ClockCircleOutlined,
  SyncOutlined,
  MessageOutlined,
  QuestionCircleOutlined,
  UserOutlined,
  AreaChartOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  InfoCircleOutlined,
  FileSearchOutlined,
  FundOutlined,
  CloudOutlined
} from '@ant-design/icons';
import { Line, Pie, Column } from '@ant-design/charts';
import { useThemeStore } from '../stores/themeStore';

const Dashboard: React.FC = () => {
  const { isDarkMode } = useThemeStore();
  const [loading, setLoading] = useState(true);
  const [dashboardData, setDashboardData] = useState<any>(null);
  
  // 模拟加载数据
  useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        // 实际项目中这里会调用API
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 模拟数据
        setDashboardData({
          stats: {
            totalDocuments: 1284,
            documentsToday: 28,
            totalUsers: 76,
            activeModels: 5,
            querySuccessRate: 94.2,
            avgResponseTime: 1.2,
            storageUsage: 68.5
          },
          recentDocuments: [
            { id: '1', name: '产品开发规范V2.3.pdf', type: 'pdf', status: 'processed', size: 4850000, updatedAt: '2023-11-15T08:30:00Z' },
            { id: '2', name: '市场分析报告2023Q4.docx', type: 'docx', status: 'processed', size: 2340000, updatedAt: '2023-11-14T15:20:00Z' },
            { id: '3', name: '技术架构设计.md', type: 'md', status: 'processing', size: 154000, updatedAt: '2023-11-13T09:45:00Z' },
            { id: '4', name: '财务预算2024.xlsx', type: 'xlsx', status: 'processed', size: 980000, updatedAt: '2023-11-11T11:30:00Z' },
            { id: '5', name: '客户反馈汇总.txt', type: 'txt', status: 'pending', size: 125000, updatedAt: '2023-11-10T16:15:00Z' }
          ],
          topQueries: [
            { query: "产品定价策略", count: 87, avgRelevance: 0.92 },
            { query: "研发流程文档", count: 65, avgRelevance: 0.88 },
            { query: "销售培训材料", count: 54, avgRelevance: 0.95 },
            { query: "市场竞争分析", count: 42, avgRelevance: 0.76 },
            { query: "技术架构图", count: 39, avgRelevance: 0.89 }
          ],
          documentsByType: [
            { type: "PDF", value: 426 },
            { type: "Word", value: 349 },
            { type: "Excel", value: 215 },
            { type: "Markdown", value: 156 },
            { type: "Text", value: 98 },
            { type: "其他", value: 40 }
          ],
          queryTrend: Array(30).fill(0).map((_, i) => ({
            date: `2023-${10 + Math.floor(i / 30)}-${(i % 30) + 1}`,
            queries: 50 + Math.floor(Math.random() * 100),
            avgScore: 0.7 + (Math.random() * 0.25)
          })),
          systemAlerts: [
            { id: '1', type: 'warning', message: '系统存储空间已使用68.5%，建议清理旧文档', time: '10分钟前' },
            { id: '2', type: 'info', message: '系统已完成每日索引优化', time: '2小时前' },
            { id: '3', type: 'success', message: '成功集成新的GPT-4-Turbo模型', time: '1天前' },
          ],
          activeUsers: [
            { id: '1', name: '张三', role: '管理员', avatar: 'https://randomuser.me/api/portraits/men/1.jpg', activity: '上传了5份文档' },
            { id: '2', name: '李四', role: '开发人员', avatar: 'https://randomuser.me/api/portraits/women/2.jpg', activity: '更新了API设置' },
            { id: '3', name: '王五', role: '分析师', avatar: 'https://randomuser.me/api/portraits/men/3.jpg', activity: '调整了检索参数' },
            { id: '4', name: '赵六', role: '内容管理员', avatar: 'https://randomuser.me/api/portraits/women/4.jpg', activity: '整理了文档标签' }
          ]
        });
        
        setLoading(false);
      } catch (error) {
        console.error('Error fetching dashboard data:', error);
        setLoading(false);
      }
    };
    
    fetchDashboardData();
  }, []);
  
  // 如果数据正在加载中，显示骨架屏
  if (loading || !dashboardData) {
    return (
      <div style={{ padding: '20px 0' }}>
        <Row gutter={[16, 16]}>
          {Array(8).fill(null).map((_, i) => (
            <Col xs={24} sm={12} md={6} key={i}>
              <Card loading={true} />
            </Col>
          ))}
        </Row>
      </div>
    );
  }
  
  // 渲染图表
  const renderDocumentTypePie = () => {
    const config = {
      data: dashboardData.documentsByType,
      angleField: 'value',
      colorField: 'type',
      radius: 0.8,
      label: false,
      tooltip: {
        formatter: (datum: any) => {
          return { name: datum.type, value: `${datum.value} 个文档` };
        },
      },
      legend: {
        position: 'bottom',
      },
      interactions: [{ type: 'element-active' }],
      theme: isDarkMode ? 'dark' : 'light',
    };
    
    return <Pie {...config} />;
  };
  
  const renderQueryTrendLine = () => {
    const config = {
      data: dashboardData.queryTrend,
      xField: 'date',
      yField: 'queries',
      smooth: true,
      yAxis: {
        label: {
          formatter: (v: string) => `${v}`,
        },
      },
      tooltip: {
        showMarkers: true,
      },
      theme: isDarkMode ? 'dark' : 'light',
      areaStyle: () => {
        return {
          fill: 'l(270) 0:#ffffff00 0.5:#1890ff66 1:#1890ffaa',
        };
      },
    };
    
    return <Line {...config} />;
  };
  
  const renderTopQueriesBarChart = () => {
    const config = {
      data: dashboardData.topQueries,
      xField: 'count',
      yField: 'query',
      seriesField: 'query',
      legend: false,
      meta: {
        count: {
          alias: '查询次数',
        },
      },
      label: {
        position: 'right',
      },
      tooltip: {
        formatter: (datum: any) => {
          return { name: datum.query, value: `${datum.count} 次查询，相关度 ${(datum.avgRelevance * 100).toFixed(0)}%` };
        },
      },
      theme: isDarkMode ? 'dark' : 'light',
    };
    
    return <Column {...config} />;
  };
  
  // 获取文档状态标签颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'processed': return 'success';
      case 'processing': return 'processing';
      case 'pending': return 'warning';
      case 'error': return 'error';
      default: return 'default';
    }
  };
  
  // 格式化文件大小
  const formatFileSize = (size: number) => {
    if (size < 1024) {
      return `${size} B`;
    } else if (size < 1024 * 1024) {
      return `${(size / 1024).toFixed(2)} KB`;
    } else if (size < 1024 * 1024 * 1024) {
      return `${(size / (1024 * 1024)).toFixed(2)} MB`;
    } else {
      return `${(size / (1024 * 1024 * 1024)).toFixed(2)} GB`;
    }
  };
  
  return (
    <div className="dashboard-container">
      {/* 系统状态概览 */}
      <Card style={{ marginBottom: 16 }}>
        <Alert
          message="系统状态良好"
          description={
            <div>
              <p>知识库平台运行正常，所有服务都可用。存储使用率为 {dashboardData.stats.storageUsage}%，查询成功率 {dashboardData.stats.querySuccessRate}%。</p>
              <div style={{ marginTop: 8 }}>
                <Space>
                  <Button type="primary" icon={<FileTextOutlined />}>添加文档</Button>
                  <Button icon={<FileSearchOutlined />}>检索测试</Button>
                </Space>
              </div>
            </div>
          }
          type="success"
          showIcon
        />
      </Card>
      
      <Row gutter={[16, 16]}>
        {/* 统计卡片 */}
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic 
              title="文档总数"
              value={dashboardData.stats.totalDocuments}
              prefix={<FileTextOutlined />}
              suffix={
                <Tooltip title="今日新增">
                  <Tag color="blue">+{dashboardData.stats.documentsToday}</Tag>
                </Tooltip>
              }
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic 
              title="团队成员"
              value={dashboardData.stats.totalUsers}
              prefix={<TeamOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic 
              title="活跃模型数"
              value={dashboardData.stats.activeModels}
              prefix={<ApiOutlined />}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic 
              title="存储使用率"
              value={dashboardData.stats.storageUsage}
              precision={1}
              suffix="%"
              prefix={<CloudOutlined />}
              valueStyle={{ color: dashboardData.stats.storageUsage > 80 ? '#ff4d4f' : '#3f8600' }}
            />
            <Progress 
              percent={dashboardData.stats.storageUsage} 
              status={dashboardData.stats.storageUsage > 80 ? 'exception' : 'normal'} 
              showInfo={false} 
              strokeWidth={5}
              style={{ marginTop: 8 }}
            />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* 性能指标 */}
        <Col xs={24} sm={12} md={8}>
          <Card title="检索性能" extra={<SyncOutlined />}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span>查询成功率</span>
                  <span>{dashboardData.stats.querySuccessRate}%</span>
                </div>
                <Progress 
                  percent={dashboardData.stats.querySuccessRate} 
                  status={dashboardData.stats.querySuccessRate > 90 ? 'success' : 'normal'}
                  strokeWidth={5}
                />
              </div>
              
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span>平均响应时间</span>
                  <span>{dashboardData.stats.avgResponseTime}秒</span>
                </div>
                <Progress 
                  percent={(1 - dashboardData.stats.avgResponseTime / 5) * 100} // 假设5秒为最大值
                  strokeWidth={5}
                  status={dashboardData.stats.avgResponseTime < 2 ? 'success' : 'normal'}
                />
              </div>
              
              <div>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span>活跃模型数</span>
                  <span>{dashboardData.stats.activeModels}</span>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  {Array(dashboardData.stats.activeModels).fill(null).map((_, i) => (
                    <Tag key={i} color="blue" style={{ margin: 0, flex: 1, textAlign: 'center' }}>
                      模型{i + 1}
                    </Tag>
                  ))}
                </div>
              </div>
            </div>
          </Card>
        </Col>
        
        <Col xs={24} sm={12} md={8}>
          <Card title="系统通知" extra={<Button type="text" size="small">全部</Button>}>
            <List
              itemLayout="horizontal"
              dataSource={dashboardData.systemAlerts}
              renderItem={(item: any) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={
                      <Avatar icon={
                        item.type === 'success' ? <CheckCircleOutlined style={{ color: '#52c41a' }} /> :
                        item.type === 'warning' ? <ExclamationCircleOutlined style={{ color: '#faad14' }} /> :
                        <InfoCircleOutlined style={{ color: '#1890ff' }} />
                      } />
                    }
                    title={item.message}
                    description={item.time}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
        
        <Col xs={24} sm={24} md={8}>
          <Card title="活跃用户" extra={<Button type="text" size="small">查看全部</Button>}>
            <List
              itemLayout="horizontal"
              dataSource={dashboardData.activeUsers}
              renderItem={(item: any) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar src={item.avatar} />}
                    title={<Space><span>{item.name}</span><Tag>{item.role}</Tag></Space>}
                    description={item.activity}
                  />
                </List.Item>
              )}
            />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* 最近文档 */}
        <Col xs={24} lg={12}>
          <Card title="最近处理的文档" extra={<Button type="link">查看全部</Button>}>
            <Table
              dataSource={dashboardData.recentDocuments}
              columns={[
                {
                  title: '文档名称',
                  dataIndex: 'name',
                  key: 'name',
                  ellipsis: true,
                },
                {
                  title: '状态',
                  dataIndex: 'status',
                  key: 'status',
                  render: (status: string) => (
                    <Tag color={getStatusColor(status)}>
                      {status === 'processed' ? '已处理' : 
                       status === 'processing' ? '处理中' : 
                       status === 'pending' ? '待处理' : status}
                    </Tag>
                  ),
                  width: 100,
                },
                {
                  title: '大小',
                  dataIndex: 'size',
                  key: 'size',
                  render: (size: number) => formatFileSize(size),
                  width: 100,
                },
              ]}
              pagination={false}
              size="small"
              rowKey="id"
            />
          </Card>
        </Col>
        
        {/* 查询趋势 */}
        <Col xs={24} lg={12}>
          <Card title="查询趋势" extra={<FundOutlined />}>
            <div style={{ height: 250 }}>
              {renderQueryTrendLine()}
            </div>
          </Card>
        </Col>
      </Row>
      
      <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
        {/* 文档类型分布 */}
        <Col xs={24} md={12}>
          <Card title="文档类型分布" extra={<FileSearchOutlined />}>
            <div style={{ height: 300 }}>
              {renderDocumentTypePie()}
            </div>
          </Card>
        </Col>
        
        {/* 热门查询 */}
        <Col xs={24} md={12}>
          <Card title="热门查询" extra={<BarChartOutlined />}>
            <div style={{ height: 300 }}>
              {renderTopQueriesBarChart()}
            </div>
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default Dashboard; 